<template>
  <div class="analysis-container">
    <!-- 筛选条件区域 -->
    <div class="filter-group">
      <el-select 
        v-model="queryParams.semester"
        placeholder="开课学期"
        class="filter-item"
        @change="initCourse"
        clearable
      >
        <el-option 
          v-for="(semester,index) in availableSemesters" 
          :key="index" 
          :value="semester"
          :label="semester"
        />
      </el-select>
      <el-select
        filterable
        v-model="queryP.selectCourseId"
        placeholder="课程"
        class="filter-item"
        @change="initClass"
        clearable
      >
        <el-option
          v-for="(item, index) in courseList1"
          :key="index"
          :label="item.courseName"
          :value="item.subId"
        />
      </el-select>
      <el-select
      filterable
        v-model="queryP.selectClassId"
        placeholder="班级"
        class="filter-item"
        @change="fetchData"
        clearable
      >
        <el-option
          v-for="(item, index) in classList"
          :key="index"
          :label="item.className"
          :value="item.classId"
        />
      </el-select>
    </div>
 <!-- 统计概览卡片 -->
    <el-row :gutter="20" class="stats-group">
      <el-col :span="8">
        <el-card class="stats-card" shadow="hover">
          <div slot="header" class="card-header">
            <i class="el-icon-data-analysis"></i>
            <span>成绩概览</span>
          </div>
          <div class="stat-item primary">
            <label>最高分</label>
            <span class="value" >{{ maxScore }}</span>
          </div>
          <div class="stat-item warning">
            <label>最低分</label>
            <span class="value">{{ minScore }}</span>
          </div>
          <div class="stat-item success">
            <label>平均分</label>
            <span class="value">{{ avgScore.toFixed(1) }}</span>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="16">
        <el-card class="chart-card" shadow="hover">
          <div slot="header" class="card-header">
            <i class="el-icon-pie-chart"></i>
            <span>等级分布</span>
          </div>
          <div ref="gradeChart" class="chart-content"></div>
        </el-card>
      </el-col>
    </el-row>

     <!-- 分段分析卡片 -->
    <el-card class="chart-card" shadow="hover">
      <div slot="header" class="card-header">
        <i class="el-icon-data-line"></i>
        <span>分段对比</span>
        <el-tag type="info" size="mini">单位：人数</el-tag>
      </div>
      <div ref="segmentChart" class="chart-content"></div>
    </el-card>


 <!-- 趋势分析卡片 -->
    <el-card class="chart-card" shadow="hover">
      <div slot="header" class="card-header">
        <i class="el-icon-trend-charts"></i>
        <span>成绩趋势</span>
        <el-tag type="info" size="mini">滚动查看</el-tag>
      </div>
      <div ref="lineChart" class="chart-content"></div>
    </el-card>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import { getDev ,getCourse,getClass} from '@/api/student'
import { getSemester } from '@/api/dashboard';

export default {
  data() {
    return {
      availableSemesters: [],
      // 新增图表实例
      lineChart: null,
      gradeChart: null,
      segmentChart: null,
      courseList1:[],//课程列表
      classList:[],//选择的课程id
      rawData:[],
      queryParams:{
        pageNum:1,
        pageSize:50,
      },
      queryP:{
        selectClassId:'',
        selectCourseId:'',
      },
    };
  },
  computed: {
    // 新增分项数据计算
    scoreCategories() {
      return {
        midTerm: this.rawData.map(item => item.halfScore),
        finalTerm: this.rawData.map(item => item.score),
        usualGrade: this.rawData.map(item => item.dayScore),
        experimentGrade: this.rawData.map(item => item.experScore)
      };
    },
    studentIds() {
      return this.rawData.map(item => item.studentId);
    },
    courseList() {
      return [...new Set(this.rawData.map(item => ({
        id: item.subId,
        name: item.courseName
      })))
      ];
    },
    totalScores() {
      return this.rawData.map(item =>
        item.sumScore
      );
    },
    // 基础统计
    maxScore() {
      
      if(Math.max(...this.totalScores).toFixed(1)=="-Infinity"){
        return 0
      }else{
        return Math.max(...this.totalScores).toFixed(1);
      }

    },
    minScore() {
      if(Math.min(...this.totalScores).toFixed(1)=="Infinity"){
        return 0
      }else{
        return Math.min(...this.totalScores).toFixed(1);
      }
    },
    avgScore() {
      if(Math.min(...this.totalScores).toFixed(1)=="Infinity"){
        return 0
      }else{
        return this.totalScores.reduce((a, b) => a + b, 0) / this.totalScores.length;
      }

    },
    // 等级分布
    gradeDistribution() {
      const levels = { 优秀: 0, 良好: 0, 合格: 0, 不合格: 0 };
      this.totalScores.forEach(score => {
        if (score >= 90) levels.优秀++;
        else if (score >= 80) levels.良好++;
        else if (score >= 60) levels.合格++;
        else levels.不合格++;
      });
      return levels;
    },
    // 修改后的分段统计计算属性
      scoreSegments() {
      // 初始化10个分段（0-10, 10-20,...,90-100）
      const segments = Array.from({length: 10}, (_, i) => ({
        range: `${i*10}-${(i+1)*10}`,
        scoreCount: 0,      // 期末成绩
        dayScoreCount: 0,   // 平时成绩
        halfScoreCount: 0,  // 期中成绩
        expScoreCount: 0    // 实验成绩
      }));

      // 遍历所有数据进行统计
      this.rawData.forEach(student => {
        // 统计期末成绩
        this.countScore(segments, student.score, 'scoreCount');
        // 统计平时成绩
        this.countScore(segments, student.dayScore, 'dayScoreCount');
        // 统计期中成绩
        this.countScore(segments, student.halfScore, 'halfScoreCount');
        // 统计实验成绩
        this.countScore(segments, student.experScore, 'expScoreCount');
      });

      return segments;
    }
  },
  mounted() {
    getSemester().then(res=>
      this.availableSemesters=res.data
    )
  },
  methods: {
    initCourse(semester){
      getCourse(semester).then(res=>{
            this.courseList1=res.data;
      })
    },
    // 通用分数统计方法
    countScore(segments, score, field) {
      const index = Math.min(Math.floor(score/10), 9);
      segments[index][field]++;
    },
     // 获取后端数据
     select(){
      getCourse().then(res=>{
        console.log(res.data);
        this.courseList1=res.data;
      })

    },
    initClass(courseId){
      getClass(courseId).then(res => {
        this.classList=res.data;
      })
    },
 // 新增折线图初始化方法
    initLineChart() {
      if (!this.$refs.lineChart) return;
      
      // 销毁旧实例
      if (this.lineChart) {
        this.lineChart.dispose();
      }
      
      this.lineChart = echarts.init(this.$refs.lineChart);
      const option = {
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: ['期中成绩', '期末成绩', '平时成绩', '实验成绩']
        },
        xAxis: {
          type: 'category',
          data: this.studentIds,
          name: '学生学号',
          axisLabel: {
            rotate: 45 // 学号较多时旋转显示
          }
        },
        yAxis: {
          type: 'value',
          name: '分数',
          min: 0,
          max: 100
        },
        series: [
          {
            name: '期中成绩',
            type: 'line',
            data: this.scoreCategories.midTerm,
            itemStyle: { color: '#5470C6' }
          },
          {
            name: '期末成绩',
            type: 'line',
            data: this.scoreCategories.finalTerm,
            itemStyle: { color: '#91CC75' }
          },
          {
            name: '平时成绩',
            type: 'line',
            data: this.scoreCategories.usualGrade,
            itemStyle: { color: '#FAC858' }
          },
          {
            name: '实验成绩',
            type: 'line',
            data: this.scoreCategories.experimentGrade,
            itemStyle: { color: '#EE6666' }
          }
        ],
        dataZoom: [{
          type: 'slider',
          start: 0,
          end: 50,
          bottom: 20,
          fillerColor: 'rgba(64,158,255,0.2)'
        }],
        grid: {
          top: 60,
          bottom: 100
        }
      };
      this.lineChart.setOption(option);
    },

    // 获取后端数据
    async fetchData() {
      try {
        const res = await getDev(this.queryP); // 直接 await
        console.log('API响应数据:', res.data);
        // 确保数据结构正确
        if (res && res.data) {
          this.rawData = res.data;
          this.initGradeChart();
          this.initSegmentChart();
          // 新增折线图渲染
          this.initLineChart();
        } else {
          throw new Error('响应数据格式错误');
        }
      } catch (error) {
        console.error('数据加载失败:', error);
      }
    },

    initGradeChart() {
      this.gradeChart = echarts.init(this.$refs.gradeChart);
      const gradeOption = {
            title: {
              text: '成绩等级分布',
              left: 'center',
              textStyle: {
                fontSize: 16,
                color: '#333'
              }
            },
            legend: {
              orient: 'vertical',
              right: 20,
              top: 'middle',
              data: Object.keys(this.gradeDistribution)
            },
            tooltip: {
              formatter: ({ name, value, percent }) => `
                <div style="padding:5px">
                  <strong>${name}</strong><br/>
                  人数: ${value}<br/>
                  占比: ${percent}%
                </div>
              `
            },
             series: [{
              type: 'pie',
              radius: ['45%', '70%'],
              data: Object.entries(this.gradeDistribution).map(([name, value]) => ({
                name,
                value,
                itemStyle: { 
                  color: this.getLevelColor(name),
                  borderWidth: 2,
                  borderColor: '#fff'
                }
              })),
              label: {
                show: true,
                formatter: '{b}: {d}%',
                fontSize: 12
              }
            }]
      };
      this.gradeChart.setOption(gradeOption);
    },

    // 修改后的分段图表初始化方法
    initSegmentChart() {
      this.segmentChart = echarts.init(this.$refs.segmentChart);
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: { type: 'shadow' },
          formatter: params => {
            let tip = `区间: ${params[0].name}<br>`;
            params.forEach(item => {
              tip += `${item.marker} ${item.seriesName}: ${item.value}人<br>`;
            });
            return tip;
          }
        },
        legend: {
          data: ['期末成绩', '平时成绩', '期中成绩', '实验成绩']
        },
        xAxis: {
          type: 'category',
          data: this.scoreSegments.map(s => s.range),
          name: '分数区间'
        },
        yAxis: {
          type: 'value',
          name: '人数'
        },
        series: [
          {
            name: '期末成绩',
            type: 'bar',
            data: this.scoreSegments.map(s => s.scoreCount),
            itemStyle: { color: '#5470C6' },
            barWidth: '15%'
          },
          {
            name: '平时成绩',
            type: 'bar',
            data: this.scoreSegments.map(s => s.dayScoreCount),
            itemStyle: { color: '#91CC75' },
            barWidth: '15%'
          },
          {
            name: '期中成绩',
            type: 'bar',
            data: this.scoreSegments.map(s => s.halfScoreCount),
            itemStyle: { color: '#FAC858' },
            barWidth: '15%'
          },
          {
            name: '实验成绩',
            type: 'bar',
            data: this.scoreSegments.map(s => s.expScoreCount),
            itemStyle: { color: '#EE6666' },
            barWidth: '15%'
          }
        ]
      };
      this.segmentChart.setOption(option);
    },
    getLevelColor(level) {
      const colors = { 优秀: '#67C23A', 良好: '#409EFF', 合格: '#E6A23C', 不合格: '#F56C6C' };
      return colors[level];
    },
    getSegmentColor(index) {
      return index >= 8 ? '#F56C6C' :
        index >= 6 ? '#E6A23C' :
          index >= 4 ? '#409EFF' : '#67C23A';
    }
  },
  beforeDestroy() {
    // 新增实例销毁
    if (this.lineChart) {
      this.lineChart.dispose();
    }
  }
};
</script>
<style scoped>
.analysis-container {
  padding: 20px;
  background: #f5f7fa;
  min-height: 100vh;
}

/* 筛选条件 */
.filter-group {
  display: flex;
  gap: 12px;
  margin-bottom: 20px;
  flex-wrap: wrap;
}
.filter-item {
  width: 240px;
}

/* 统计卡片 */
.stats-group {
  margin-bottom: 20px;
}
.stats-card {
  border-radius: 8px;
  height: 100%;
}
.stats-card::v-deep .el-card__header {
  padding: 16px 20px;
  background: linear-gradient(120deg, #f0f2f5 0%, #ffffff 100%);
}
.stat-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  margin: 8px 0;
  border-radius: 4px;
}
.stat-item label {
  color: #606266;
  font-size: 14px;
}
.stat-item .value {
  font-weight: 600;
  font-size: 18px;
}
.primary { background: rgba(64,158,255,0.1); color: #409EFF; }
.warning { background: rgba(230,162,60,0.1); color: #E6A23C; }
.success { background: rgba(103,194,58,0.1); color: #67C23A; }

/* 图表卡片 */
.chart-card {
  border-radius: 8px;
  margin-top: 20px;
}
.chart-card::v-deep .el-card__header {
  padding: 16px 20px;
  border-bottom: 1px solid #ebeef5;
}
.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  color: #303133;
}
.card-header i {
  font-size: 18px;
}
.chart-content {
  height: 400px;
}

/* 响应式适配 */
@media (max-width: 768px) {
  .stats-group .el-col {
    width: 100%;
    margin-bottom: 16px;
  }
  .filter-item {
    width: 100%;
  }
}
</style>
